package com.zrb.discover;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.zrb.applib.utils.AppSetting;
import com.zrb.discover.bean.UserInfoJson;
import com.zrb.discover.widget.ProfileScrollView;
import com.zrb.mobile.BaseFragmentActivity;
import com.zrb.mobile.R;
import com.zrb.mobile.adapter.model.Dynamic_AllCardDto;
import com.zrb.mobile.adapter.model.FollowDto;
import com.zrb.mobile.fadingactionbar.ActionBarHelper;
import com.zrb.mobile.fadingactionbar.SherlockFadingActionBarHelper;
import com.zrb.mobile.register.User_phone_login;
 
import com.zrb.mobile.ui.CircleImageView;
import com.zrb.mobile.ui.SimpleViewPagerIndicator;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.FollowRelationUtil;
import com.zrb.mobile.utility.ProgressDialogEx;
import com.zrb.mobile.utility.Tip;
import com.zrb.mobile.utility.ViewUtil;
import com.zrb.mobile.utility.ZrbRestClient;
import com.zrb.mobile.utility.ZrbRestClient.HttpResponseListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class UserCardDetailActivity extends SherlockFragmentActivity implements OnClickListener {
	private String[] mTitles = new String[] { "动态", "精选" };
	
 
	public  static final String USER_ID = "userId";
	public  static final String USER_NAME = "name";
	public  static final String USER_ORG = "org";
	public  static final String USER_INDUSTRY = "industry";
	public  static final String USER_JOB = "job";
	public  static final String USER_AVATAR_URL = "avatar";
	public  static final String USER_INTENTION_ID = "intentionId";
	private ViewGroup mInnerScrollView;
	View customNav;
	private SimpleViewPagerIndicator mIndicator;
	private ViewPager mViewPager;
	private FragmentPagerAdapter mAdapter;
	private List<Fragment> fragments = new ArrayList<Fragment>();
	private int mCurrentPage = 0;
	ZrbRestClient mZrbRestClient;
	private String mUserName = "";
	private String mAvatarUrl = "";
	private String mOrg = "";
	private String mIndustry = "";
	private String mJob = "";
	private Long mUserId = 0l;
	Dynamic_AllCardDto userInfo;
	private CircleImageView mCircleImageView = null;
	private TextView mUserNameView = null;
	private TextView mJobView = null;
	Handler myhandler = new Handler();
	 Tip	progTip ;
	int mCurrentPosition=0;
	 
	 ProfileScrollView rootScrolView;
	 TextView tabtext1,tabtext2;
	 TextView followBtn;  
	 public Handler getHandler(){
		 return myhandler;
	 }
 
	 
	public static void launch(Context mActivity, long userId, String name, String avatar, String org, String job, String industry) {
		Intent it = new Intent(mActivity, UserCardDetailActivity.class);
		it.putExtra(USER_ID, userId);
		it.putExtra(USER_NAME, name);
		it.putExtra(USER_AVATAR_URL, avatar);
		it.putExtra(USER_ORG, org);
		it.putExtra(USER_JOB, job);
		it.putExtra(USER_INDUSTRY, industry);

		mActivity.startActivity(it);
	}
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.dynamic_user_card);

		mUserName = getIntent().getStringExtra(USER_NAME);
		mUserId = getIntent().getLongExtra(USER_ID, 0);
		mAvatarUrl = getIntent().getStringExtra(USER_AVATAR_URL);
		mOrg = getIntent().getStringExtra(USER_ORG);
		mJob = getIntent().getStringExtra(USER_JOB);
		mIndustry = getIntent().getStringExtra(USER_INDUSTRY);

		getSupportActionBar().setDisplayShowTitleEnabled(false);
		getSupportActionBar().setDisplayShowHomeEnabled(false);

		customNav = LayoutInflater.from(this).inflate(R.layout.project_fadingbar, null);
		getSupportActionBar().setCustomView(customNav);
		getSupportActionBar().setDisplayShowCustomEnabled(true);
		initView();
		loadUserDescriptionData();
	}
 
	 
	
	private void initView() {

		mCircleImageView = (CircleImageView) this.findViewById(R.id.business_user_avatar);
		mUserNameView = (TextView) this.findViewById(R.id.business_user_name);
		mJobView = (TextView) this.findViewById(R.id.business_user_job);
		followBtn= (TextView) this.findViewById(R.id.tv_follow_btn);
		followBtn.setOnClickListener(this);
		
		
		if(AppSetting.curUser!=null&&mUserId==AppSetting.curUser.uid) followBtn.setVisibility(View.INVISIBLE);
		rootScrolView =(ProfileScrollView)this.findViewById(R.id.rootScrolView2);
		rootScrolView.initActionBar(R.drawable.app_bg3, this);
		 
	 	View lefticon = customNav.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this);
	/*	TextView txtTitle = (TextView) this.findViewById(R.id.txt_title);
		txtTitle.setVisibility(View.GONE); */ 
		mIndicator = (SimpleViewPagerIndicator) findViewById(R.id.id_stickynavlayout_indicator);
		mIndicator.setTitles(mTitles);
		mIndicator.setColor(Color.parseColor("#999999"), Color.parseColor("#007de3"));
  		 
		
		tabtext1=	mIndicator.getTextViewAt(0);
		tabtext1.setCompoundDrawablesWithIntrinsicBounds (UserCardDetailActivity.this.getResources().getDrawable(R.drawable.dynamic_text_tab1), null, null, null);
		tabtext1.setCompoundDrawablePadding(CommonUtil.dip2px(UserCardDetailActivity.this, 5));
 
		
		tabtext2=	mIndicator.getTextViewAt(1);
		tabtext2.setCompoundDrawablesWithIntrinsicBounds (UserCardDetailActivity.this.getResources().getDrawable(R.drawable.dynamic_text_tab2), null, null, null);
		tabtext2.setCompoundDrawablePadding(CommonUtil.dip2px(UserCardDetailActivity.this, 5));
 		
		mIndicator.setSelectTextAt(0);
		mViewPager = (ViewPager) findViewById(R.id.id_stickynavlayout_viewpager);
		mViewPager.setOffscreenPageLimit(0);
  	}

	private void initPager(){
		/*fragments.add(UserCard_FundTabFragment.newInstance("动态",mUserId+""));
 		fragments.add(UserCard_DynamictFragment.getNewFrament( userInfo.dynamicList));*/
 		
		 //fragments.add(UserCard_IntentTabFragment.newInstance("publish", mUserId+"", userInfo.dynamicList));
		fragments.add(UserCard_DynamictFragment.getNewFrament( userInfo.dynamicList, mUserId+""));
		fragments.add(UserCard_ChoicenessFragment.getNewFrament(userInfo.choiceGeneralList,  mUserId+""));
		
 		
		
		mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
			@Override
			public int getCount() {
				return mTitles.length;
			}

			@Override
			public Fragment getItem(int position) {
				return fragments.get(position);
 			}

		};
		
		mViewPager.setAdapter(mAdapter);
		mViewPager.setCurrentItem(0);
 		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				
				CommonUtil.InfoLog("onPageSelected", "onPageSelected:"+position);
				if(position==0){
					mIndicator.setSelectTextAt(0);
				} 
				else{
					mIndicator.setSelectTextAt(1);
					((UserCard_ChoicenessFragment)fragments.get(1)).firstLoad();
 				 }
				 getCurrentScrollView();
					
			}

			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
				mIndicator.scroll(position, positionOffset);
			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}
		});
 		
 		myhandler.postDelayed(initCurrentFragment, 300);
	}
	
	Runnable initCurrentFragment = new Runnable() {

        @Override
        public void run() {
            if (getCurrentFragment() != null ) {
               // rootScrolView.setAbsListView(((ARefreshFragment) getCurrentFragment()).getRefreshView());
            	getCurrentScrollView();
            }
            else {
            	myhandler.postDelayed(initCurrentFragment, 100);
            }
        }

    };
	
    
    public Fragment getCurrentFragment() {
        if (mViewPager == null )//|| mViewPager.getCount() < mCurrentPosition
            return null;

        return fragments.get(mCurrentPosition);
    }
	
	private void getCurrentScrollView()
	{

		int currentItem = mViewPager.getCurrentItem();
		PagerAdapter a = mViewPager.getAdapter();
		if (a instanceof FragmentPagerAdapter)
		{
			FragmentPagerAdapter fadapter = (FragmentPagerAdapter) a;
			Fragment item = fadapter.getItem(currentItem);
			mInnerScrollView = (ViewGroup) (item.getView()
					.findViewById(R.id.id_stickynavlayout_innerscrollview));
			
			rootScrolView.setAbsListView(mInnerScrollView);
		} else if (a instanceof FragmentStatePagerAdapter)
		{
			FragmentStatePagerAdapter fsAdapter = (FragmentStatePagerAdapter) a;
			Fragment item = fsAdapter.getItem(currentItem);
			mInnerScrollView = (ViewGroup) (item.getView()
					.findViewById(R.id.id_stickynavlayout_innerscrollview));
		}
		
	}
   /* public void onPageSelected(int position) {
        super.onPageSelected(position);

        // 设置当前选中tab的滚动视图，用来判断手势
        ABaseFragment fragment = (ABaseFragment) getCurrentFragment();
        if (fragment != null) {
            if (fragment instanceof ARefreshFragment) {
                AbsListView refreshView = ((ARefreshFragment) fragment).getRefreshView();
                rootScrolView.setAbsListView(refreshView);
            } else if (fragment instanceof UserProfileTab1Fragment) {
                UserProfileTab1Fragment tab1Fragment = (UserProfileTab1Fragment) fragment;
                rootScrolView.setAbsListView(tab1Fragment.getScrollView());
            }
        }
    }*/
	
	private void loadUserDescriptionData() {
		RequestParams param = new RequestParams();
		param.put("userId", mUserId);
  
		if (mZrbRestClient == null) {
			mZrbRestClient = new ZrbRestClient(this);
		}
		mZrbRestClient.setOnhttpResponseListener(new HttpResponseListener() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {

				CommonUtil.showToast(R.string.error_net_loadfail, UserCardDetailActivity.this);
				//completeRefresh();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String results = new String(arg2);
				try {
					
					JSONObject jsonObject2 =new JSONObject(results);
					int retCode= jsonObject2.getInt("res");
					if(retCode==1){
						
						Gson gson = new Gson();
						Dynamic_AllCardDto fundJson = gson.fromJson(jsonObject2.getString("data"), Dynamic_AllCardDto.class);
 						if (fundJson != null) {
							userInfo = fundJson;
							mUserName = userInfo.realName;//.realName;
							mAvatarUrl = userInfo.avatar;//.avatar;
							mOrg = userInfo.org;//.org;
							mJob = userInfo.position;
							mIndustry = userInfo.industryName;//.industry;
 
						} else {
							CommonUtil.showToast(String.format("暂无%1$s信息~~", mCurrentPage == 0 ? "" : "更多"), UserCardDetailActivity.this);
						}
					 }
 				   else {
						CommonUtil.showToast(jsonObject2.getString("msg"), UserCardDetailActivity.this);
					}
				} catch (Exception e) {
					CommonUtil.showToast(R.string.error_serverdata_loadfail, UserCardDetailActivity.this);
				}
				fillData();
				//requestIntentionList();
			}
		});
		mZrbRestClient.post("businessCard/myCard", param);
	}
	
	private void fillData(){
		 
		if(!TextUtils.isEmpty(mAvatarUrl)) ViewUtil.showUserAvatar(mCircleImageView,mAvatarUrl);
		
		if(TextUtils.isEmpty(mUserName)){
			mUserName = getResources().getString(R.string.anonymity);
		}
		mUserNameView.setText(mUserName);
		String str = "";
		if(!TextUtils.isEmpty(mIndustry)){
			str = mIndustry;
		}
		if(!TextUtils.isEmpty(mOrg)){
			if(!TextUtils.isEmpty(mIndustry)){
				str = str + Constants.FLAG;
			}
			str = str + mOrg;
		}
		if(!TextUtils.isEmpty(mJob)){
			if(!TextUtils.isEmpty(mIndustry) || !TextUtils.isEmpty(mOrg)){
				str = str + Constants.FLAG;
			}
			str = str + mJob;
		}
		if(TextUtils.isEmpty(str)){
			str = getResources().getString(R.string.secrecy);
		}
		mJobView.setText(str);   
		
		if(userInfo!=null){
 			tabtext1.setText(mTitles[0]+" "+userInfo.dynamicCount);
 			tabtext2.setText(mTitles[1]+" "+userInfo.choiceCount);
 			followBtn.setText(FollowRelationUtil.getRelationdes(userInfo.relationCode));
 		}
		
		initPager();
	}
	
	public void showloading() {
		if (progTip == null)
			progTip = ProgressDialogEx.Show(this, " title", "正在加载中...", true,
					true);
		else
			progTip.Show("正在加载中...");
	}
	
	public void hideloading(){
		
		if (progTip != null) progTip.Dismiss();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			this.finish();
			break;
		case R.id.tv_follow_btn:
			if(userInfo!=null){
 				if(AppSetting.curUser.uid==mUserId) return;
 				checkFocus(!FollowRelationUtil.haveFollowed(userInfo.relationCode),mUserId);//0未关注 ,1已关注，2被关注 3相互关注
			}
			break;
			
		}
	}

	private void checkFocus(boolean isFocus,Long userId){
		
		if (mZrbRestClient == null) {
			mZrbRestClient = new ZrbRestClient(this);
		}
		mZrbRestClient.setOnhttpResponseListener(new HttpResponseListener() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {

				CommonUtil.showToast(R.string.error_net_loadfail, UserCardDetailActivity.this);
				//completeRefresh();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String results = new String(arg2);
				try {
					Gson gson = new Gson();
					FollowDto tmpDto = gson.fromJson(results, FollowDto.class);
					
					 if(tmpDto.res==1){
						 userInfo.relationCode=tmpDto.data.relation;
						 CommonUtil.showToast(FollowRelationUtil.haveFollowed(tmpDto.data.relation)?"关注成功":"取消关注成功");
						 followBtn.setText(FollowRelationUtil.getRelationdes(tmpDto.data.relation));
 				    }
 				     else {
						CommonUtil.showToast(tmpDto.msg);
					}
				} catch (Exception e) {
					CommonUtil.showToast(R.string.error_serverdata_loadfail, UserCardDetailActivity.this);
				}
 
			}
		});//%1$d
		mZrbRestClient.sessionGet(String.format("userfollow/%1$s?toUserId=%2$d", isFocus? "follow":"unfollow",userId));
	}
	
}
